package com.wangwenjun.concurrency.chapter17;


import java.util.ArrayList;
import java.util.List;

/**
 * 实现一个容器，提供两个方法，add，size 写两个线程，
 * 线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束.
 */
public class TaoBaoTest {

    private List<String> list = new ArrayList<>();

    public synchronized void add(){
        for (int i = 0; i < 10 ; i++) {
            if(list.size() == 5){
                /**不会释放锁*/
                this.notify();
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            list.add(i+"");
            System.out.println(Thread.currentThread().getName()+" add "+i);
        }
    }

    public synchronized void size(){
        if(list.size() != 5){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(Thread.currentThread().getName()+" 个数已达5个");
        this.notify();
    }

    public static void main(String[] args) {
        TaoBaoTest test = new TaoBaoTest();
        new Thread(()->{
            test.size();
        }, "t1").start();

        new Thread(()->{
            test.add();
        }, "t2").start();
    }

}
